//
// Created by zx208 on 2024/10/27.
//

#include "SequenceQueue.h"

Status InitQueue(SqQueue *Q) {
    Q->base = (ElemType *)malloc(sizeof(ElemType) * MAXQUEUE);
    if (!Q->base) exit(OVERFLOW);
    Q->front = Q->rear = 0; // 把 front 和 rear 初始化为0
    return OK;
}

Status Entry_SQ(SqQueue *Q, ElemType e) {
    if ((Q->rear + 1) % MAXQUEUE == Q->front) // 判断是否队满
        return ERROR;
    Q->base[Q->rear] = e;
    Q->rear = (Q->rear + 1) % MAXQUEUE; // Q->rear++ 错误写法
    return OK;
}

Status Out_SQ(SqQueue *Q, ElemType *e) {
    if (Q->rear == Q->front) // 判断是否队满
        return ERROR;
    *e = Q->base[Q->front];
    Q->front = (Q->front + 1) % MAXQUEUE; // Q->front++; 为错误写法
    return OK;
}

Status IsEmpty_SQ(SqQueue *Q) {
    return Q->front == Q->rear;
}

Status IsFull_SQ(SqQueue *Q) {
    return (Q->rear + 1) % MAXQUEUE == Q->front;
}

Status GetFront(SqQueue *Q, ElemType *e) {
    if (IsEmpty_SQ(Q))
        return ERROR;
    *e = Q->base[Q->front];
    return OK;
}

int LengthQueue(SqQueue *Q) {
    return (Q->rear - Q->front + MAXQUEUE) % MAXQUEUE;
}

int main(void){
    SqQueue Q;
    InitQueue(&Q);
    Entry_SQ(&Q, 1);
    Entry_SQ(&Q, 2);
    Entry_SQ(&Q, 3);
    Entry_SQ(&Q, 4);
    printf("%d\n", LengthQueue(&Q));
    ElemType e;
    while (!(IsEmpty_SQ(&Q))) {
        Out_SQ(&Q, &e);
        printf("%d ", e);
    }
    return 0;
}